package com.exam.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exam.demo.common.Constants;
import com.exam.demo.controller.dto.UserDTO;
import com.exam.demo.entity.Admin;
import com.exam.demo.entity.Menu;
import com.exam.demo.entity.Teacher;
import com.exam.demo.exception.ServiceException;
import com.exam.demo.mapper.AdminMapper;
import com.exam.demo.mapper.TeacherMapper;
import com.exam.demo.service.AdminService;
import com.exam.demo.service.RoleService;
import com.exam.demo.service.TeacherService;
import com.exam.demo.util.ObjectMapper;
import com.exam.demo.util.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 功能描述
 *
 * @author yxj30
 * @date 2022/03/16  19:29
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    private static final Log LOG = Log.get();

    @Resource
    RoleService roleService;
    @Resource
    TeacherMapper teacherMapper;

    @Override
    public Page<Teacher> findPage(Page<Teacher> page, String teacherName) {
        return teacherMapper.findPage(page,teacherName);
    }

    @Override
    public UserDTO login(Teacher teacher) {
        Teacher one = getTeacherInfo(teacher);
        if (one != null) {
            BeanUtil.copyProperties(one, teacher, true);//把one复制给teacher
            UserDTO user = ObjectMapper.teacherToUserDTO(teacher); //把teacher转为userDTO
            // 设置token
            String token = TokenUtils.genToken(one.getTeacherId(), one.getTeacherPassword());
            user.setToken(token);
            user.setRole(Constants.ROLE_TEACHER);
            // 设置用户的菜单列表
            List<Menu> roleMenus = roleService.getRoleMenus(Constants.ROLE_TEACHER);
            user.setMenus(roleMenus);
            return user;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }

    /**
     * 根据账号和密码，查找teacher
     * @param teacher
     * @return
     */
    private Teacher getTeacherInfo(Teacher teacher) {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id",teacher.getTeacherId());
        queryWrapper.eq("teacher_password",teacher.getTeacherPassword());
        Teacher one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }
}
